/**
 * 首字母大写
 * @param str 输入字符串
 * @returns {string} 首字母大写的字符串
 */
export const titleCase = (str) => {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

/**
 * 下划线转驼峰
 * @param str 输入字符串
 * @returns {string} 驼峰格式的字符串
 */
export const camelCase = (str) => {
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

/**
 * 驼峰转下划线
 * @param str 输入字符串
 * @returns {string} 下划线格式的字符串
 */
export const underlineCase = (str) => {
  return str.replace(/([A-Z])/g, '_$1').toLowerCase()
}

/**
 * 生成随机字符串
 * @param length 字符串长度
 * @returns {string} 随机字符串
 */
export const randomString = (length = 8) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let str = ''
  for (let i = 0; i < length; i++) {
    str += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return str
}

export default {
  titleCase,
  camelCase,
  underlineCase,
  randomString
}
